package org.itsky.study.test4;

/**
 * @Author sky
 * @Site cmtianxie163.com 2020/4/16 13:56
 */

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用同步解决线程安全问题
 * 关键字 synchronzied
 * <p>
 * 同步代码块
 * 1. 代码块 ：对共享数据操作的代码块
 * 2. 同步监视器： 锁 任何一个类的对象都可以充当锁 要求：多个线程必须要公用一个锁
 */

public class SynchronizedTest {
    public static void main(String[] args) {
        MyRunnable2 runnable2 = new MyRunnable2();
        Thread t1 = new Thread(runnable2);
        Thread t2 = new Thread(runnable2);
        Thread t3 = new Thread(runnable2);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}


class MyRunnable2 implements Runnable {
    Object obj = new Object();
    private int ticket = 100;
    Lock lock = new ReentrantLock();

    @Override
    public void run() {

        while (true) {
//            synchronized (obj) {
//            synchronized (this) {
            try {
                lock.lock();
                if (ticket > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在售票" + (101 - ticket));
                    ticket--;
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }

//            }
        }


    }
}
